package com.xiaohao.healthrecords.controller;

import com.xiaohao.healthrecords.entity.HealthRecord;
import com.xiaohao.healthrecords.entity.HealthRecordDTO;
import com.xiaohao.healthrecords.entity.ResponseResult;
import com.xiaohao.healthrecords.service.HealthRecordService;
import com.xiaohao.healthrecords.service.OcrService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;
import java.util.List;

@RestController
@RequestMapping("health-record")
public class HealthRecordController {
    @Autowired
    private HealthRecordService healthRecordService;
    @Autowired
    private OcrService ocrService;

    @GetMapping("{id}")
    public ResponseResult<HealthRecord> query(@PathVariable Integer id) {
        return ResponseResult.success(healthRecordService.query(new HealthRecord().setId(id)));
    }

    @GetMapping
    public ResponseResult<List<HealthRecord>> query(HealthRecord healthRecord) {
        return ResponseResult.success(healthRecordService.queryList(healthRecord));
    }

    @PostMapping
    public ResponseResult<?> update(@RequestBody HealthRecord healthRecord) {
        if (healthRecordService.update(healthRecord) != 0) {
            return ResponseResult.success(healthRecord);
        } else {
            return ResponseResult.error();
        }
    }

    @PostMapping("ocr")
    public ResponseResult<HealthRecordDTO> ocr(@RequestPart("file") MultipartFile file) throws IOException,
        NoSuchFieldException,
        IllegalAccessException {
        return ResponseResult.success(ocrService.ocr(file.getBytes()));
    }

    @DeleteMapping("{id}")
    public ResponseResult<Void> delete(@PathVariable Integer id) {
        healthRecordService.delete(id);
        return ResponseResult.success();
    }
}
